//
//  PlayBar.swift
//  ImGuider X
//
//  Created by 王鹏宇 on 10/8/18.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit


protocol PlayBarDelegate : class {
    
    func changePointTo(index : Int)
    func downloadAction()
}

class PlayBar: UIView,WPY_AVPlayerDelegate,MyPlayProgressViewDelegate{
   
    

    var manager : WPY_AVPlayer?
    var progressBar : MyPlayProgressView!
    var currentTimeLabel : UILabel!
    var totalTimeLlabel : UILabel!
    var playBtn : UIButton!
    var nextBtn : UIButton!
    var previousBtn : UIButton!
    var speedBtn : UIButton!
    var downloadBtn : UIButton!
    var currentSpeed : Float = 1.0
    weak var  delegate : PlayBarDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        manager = WPY_AVPlayer.playManager
        manager?.delegate = self
        self.setup()
        
        NotificationCenter.default.addObserver(self, selector: #selector(playBarChangePlayStateWith(notif:)), name: NSNotification.Name(rawValue: WPY_PlayerState), object: nil)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        manager = WPY_AVPlayer.playManager
        manager?.delegate = self
        self.setup()
        
        NotificationCenter.default.addObserver(self, selector: #selector(playBarChangePlayStateWith(notif:)), name: NSNotification.Name(rawValue: WPY_PlayerState), object: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}



extension PlayBar {
    
    func setup(){
        
        progressBar = MyPlayProgressView(frame: CGRect(x: 42, y: 20, width: self.frame.size.width - 84, height: 3))
        progressBar.playProgressBackgoundColor = KThemeColor
        progressBar.trackBackgoundColor = UIColor.gray
        progressBar.delegate = self
        self.addSubview(progressBar)
        
        currentTimeLabel = UILabel(frame: CGRect(x: 16, y: 14, width: 27, height: 15))
        currentTimeLabel.text = "00:00"
        currentTimeLabel.font = UIFont.systemFont(ofSize: 9)
        currentTimeLabel.textAlignment = .center
        currentTimeLabel.textColor = kContentColor
        self.addSubview(currentTimeLabel)
        
        totalTimeLlabel = UILabel(frame: CGRect(x: self.frame.size.width - 43, y: 14, width: 27, height: 15))
        totalTimeLlabel.textAlignment = .left
        totalTimeLlabel.text = "00:00"
        totalTimeLlabel.textColor = kContentColor
        totalTimeLlabel.font = UIFont.systemFont(ofSize: 9)
        self.addSubview(totalTimeLlabel)
        
        
        
        speedBtn = UIButton(type: UIButton.ButtonType.custom)
        speedBtn.frame = CGRect(x: 16, y: 52.5, width: 40, height: 40)
        speedBtn.addTarget(self, action: #selector(changePlaySpeed), for: UIControl.Event.touchUpInside)
        speedBtn.setTitleColor(kTitleColor, for: UIControl.State.normal)
        speedBtn.titleLabel?.font = kFont14
        self.addSubview(speedBtn)
        setupSpeed()
        
        downloadBtn = UIButton(frame: CGRect(x: self.frame.size.width - 56, y: 50, width: 40, height: 40))
        downloadBtn.setTitleColor(kThemeDarkColor, for: .normal)
        downloadBtn.titleLabel?.font = kFont14
        downloadBtn.setImage(UIImage(named: "play_download"), for: UIControl.State.normal)
        downloadBtn.addTarget(self, action: #selector(download), for: UIControl.Event.touchUpInside)
        
        self.addSubview(downloadBtn)
        
        playBtn = UIButton(frame: CGRect(x: kScreenWidth/2 - 30, y:40, width: 60, height: 60))
        playBtn.setImage(UIImage(named: "lines_play"), for: UIControl.State.normal)
        playBtn.setImage(UIImage(named: "lines_pause"), for: UIControl.State.selected)
        playBtn.addTarget(self, action: #selector(playOrPause), for: UIControl.Event.touchUpInside)
        self.addSubview(playBtn)
        
        var space:CGFloat = 40.0
        if ISiPhone4 || ISiPhone5 {
            
            space = 20
        }
        
        let rect = self.playBtn.frame
        let preX = rect.minX - 35 - space
        
        previousBtn = UIButton(frame: CGRect(x: preX, y: 50, width: 40, height: 40))
        
        previousBtn.setImage(UIImage(named: "audioPre"), for: UIControl.State.normal)
        previousBtn.addTarget(self, action: #selector(previousRecord), for: UIControl.Event.touchUpInside)
        self.addSubview(previousBtn)
        
        let nextX = rect.maxX + space
        nextBtn = UIButton(frame: CGRect(x: nextX, y: 50, width: 40, height: 40))
        nextBtn.setImage(UIImage(named: "audioNext"), for: UIControl.State.normal)
        nextBtn.addTarget(self, action: #selector(nextRecord), for: UIControl.Event.touchUpInside)
        self.addSubview(nextBtn)
        
        self.backgroundColor = UIColor.white
    }
    
    func playMusicWithIndex(index : Int , immediately : Bool){
        
        self.manager?.playTheLine(index: index, isImmediately: immediately)
        self.progressBar.value = 0
        setupSpeed()
    }
    
    func setupSpeed(){
        
        self.currentSpeed = WPY_AVPlayer.playManager.playSpeed
        var str = "1.0x"//"speed1.0x"
        if self.currentSpeed == 1.25 {
            str = "1.25x" //"speed1.25x"
        }else if self.currentSpeed == 1.5 {
            str = "1.5x"//"speed1.5x"
        }
        
        speedBtn.setTitle(str, for: UIControl.State.normal)
//        speedBtn.setImage(UIImage(named: str), for: UIControl.State.normal)
    }
    
    
    @objc func changePlaySpeed(){
        
        
        if (self.currentSpeed == 1.0) {
//            speedBtn.setImage(UIImage(named: "speed1.25x"), for: UIControl.State.normal);
            speedBtn.setTitle("1.25x", for: UIControl.State.normal)
            self.currentSpeed = 1.25;
            manager?.playSpeed = 1.25;
            
        }else if(self.currentSpeed == 1.25){
//            speedBtn.setImage(UIImage(named: "speed1.5x"), for: UIControl.State.normal);
            speedBtn.setTitle("1.5x", for: UIControl.State.normal)
            self.currentSpeed = 1.5;
            self.manager?.playSpeed = 1.5;
        }else if(self.currentSpeed == 1.5){
            
//            speedBtn.setImage(UIImage(named: "speed1.0x"), for: UIControl.State.normal);
            
            speedBtn.setTitle("1.0x", for: UIControl.State.normal)
            self.currentSpeed = 1.0;
            self.manager?.playSpeed = 1.0;
        }
    }
    
    @objc func download(){
        
        delegate?.downloadAction()
    }
    
    @objc func playOrPause(){
        
        if WPY_AVPlayer.playManager.isPlay {
            
            self.manager?.pause()
        }else{
            
            self.manager?.play()
        }
       
    }
    
    @objc func previousRecord(){
        
        self.previousBtn.isUserInteractionEnabled = false
        DispatchQueue.main.after(0.5) {
            self.previousBtn.isUserInteractionEnabled = true
        }
        
        self.manager?.previous()
    }
    
    @objc func nextRecord(){
        
        self.nextBtn.isUserInteractionEnabled = false
        DispatchQueue.main.after(0.5) {
            self.nextBtn.isUserInteractionEnabled = true
        }
        
        self.manager?.next()
    }
    
    
    @objc func  playBarChangePlayStateWith(notif : Notification){
        
        
//        let url = notif.userInfo?[CurrentPlayUrl]
        if let type = notif.userInfo?[PlayType] as? WPY_AVPlayerType,type != .PlayTypeLine {
            self.progressBar.value = 0.0
            self.playBtn.setImage(UIImage(named: "lines_play"), for: UIControl.State.normal)
        }
        
        guard let state = notif.userInfo?[WPY_PlayerState] as? AVPlayerPlayState else {return}
        
        switch state {
        case AVPlayerPlayState.AVPlayerPlayStatePreparing,AVPlayerPlayState.AVPlayerPlayStateBeigin:
            
            self.playBtn.setImage(UIImage(named: "lines_pause"), for: UIControl.State.normal)
        case AVPlayerPlayState.AVPlayerPlayStatePlaying:
            
            self.playBtn.setImage(UIImage(named: "lines_pause"), for: UIControl.State.normal)
        case .AVPlayerPlayStatePause:
            
            self.playBtn.setImage(UIImage(named: "lines_play"), for: UIControl.State.normal)
        case .AVPlayerPlayStateEnd:
            self.totalTimeLlabel.text = "00:00"
            self.playBtn.setImage(UIImage(named: "lines_play"), for: UIControl.State.normal)
        
        case .AVPlayerPlayStateNotPlay:
            self.totalTimeLlabel.text = ""
            self.currentTimeLabel.text = ""
            self.progressBar.value = 0.0
            self.playBtn.setImage(UIImage(named: "lines_play"), for: UIControl.State.normal)
        case .AVPlayerPlayStateseekToZeroBeforePlay:
            self.progressBar.value = 0.0
            
        default:
            
            self.playBtn.setImage(UIImage(named: "lines_play"), for: UIControl.State.normal)
        }
    }
    
    
    
    
    func beiginSliderScrubbing() {
        
        self.manager?.isSeekingToTime = true
    }
    
    func endSliderScrubbing() {
        
        if let value = self.progressBar?.value{
            
            self.manager?.musicSeekToTime(time: Float(value))
        }
        
    }
    
    func sliderScrubbing() {
        
        guard let total = self.manager?.durantion else {return}
        
        let time = self.progressBar.value * CGFloat(total)
            
        self.currentTimeLabel.text = self.manager?.timeFormatted(totalSeconds: total  - Double(time))
    }
    
    
    
    func updateProgressWith(progress: Float) {
        
        self.progressBar.value = CGFloat(progress)
        self.totalTimeLlabel.text = self.manager?.totalTime
        self.currentTimeLabel.text = self.manager?.currentTime
    }
    
    func changeMusicToIndex(index: Int) {
        
        delegate?.changePointTo(index: index)
    }
    
    func updateBufferProgress(progress: Float) {
        
        if progress.isNaN || progress.isInfinite {
            return
        }
        self.progressBar.trackValue = CGFloat(progress) 
        self.totalTimeLlabel.text = self.manager?.totalTime
    }
    
    
}
